package com.retlife.tvshow.ui

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.KeyEvent
import com.retlife.tvshow.R
import com.retlife.tvshow.global.RunningContext
import com.retlife.tvshow.usb.UsbServer
import org.greenrobot.eventbus.EventBus

class SplashActivity : BaseActivity() {
    private var initDialog: InitDialog? = null
    private var maxConnect = 8
    private lateinit var sharedPreferences: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        EventBus.getDefault().register(this)
        sharedPreferences = getSharedPreferences(RunningContext.SP_TAG, Context.MODE_PRIVATE)
        maxConnect = sharedPreferences.getInt(RunningContext.SP_TAG, 8)
        RunningContext.maxConnect = maxConnect
        if (maxConnect == 0) {
            initDialog = InitDialog(this)
            initDialog?.show()
        } else {
            initHardware()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_splash
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.action == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                initDialog?.apply {
                    maxConnect = getCount()
                    sharedPreferences.edit().putInt(RunningContext.SP_TAG, maxConnect).apply()
                    initHardware()
                    dismiss()
                }
                return true
            }
           /* else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                initDialog?.apply {
                    pressUp()
                }
                return true
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                initDialog?.apply {
                    pressDown()
                }
                return true
            }*/
        }
        return super.onKeyDown(keyCode, event)

    }

/*
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: EventBusMsg) {
        maxConnect = event.msg as Int
        sharedPreferences.edit().putInt(RunningContext.SP_TAG, maxConnect).apply()
        initHardware()
    }
*/

    private fun initHardware() {
        RunningContext.maxConnect = maxConnect
        startService(Intent(this, UsbServer::class.java))
        Thread{
            Thread.sleep(3000)
            runOnUiThread {
                startActivity(Intent(this, MainActivity::class.java))
                finish()

            }
        }.start()
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

}